<script setup lang="ts">
// 引入用户小仓库
import useUserStore from '@/store/modules/user'
import { GET_STATE, getQueryString, SET_STATE } from '@/utils/globalUtils'
import { generateCodeVerifier } from '@/utils/pkce'
// 引入element-plus的提示框
import { ElMessage } from 'element-plus'

// 生成state
const state: string = generateCodeVerifier()

// 使用用户小仓库
const userStore = useUserStore()

// 获取地址栏授权码
const code = getQueryString('code')

if (code) {
  // 从缓存中获取 codeVerifier
  const state = GET_STATE()
  // 校验state，防止cors
  const urlState = getQueryString('state')
  if (urlState !== state) {
    ElMessage({
      message: 'state校验失败.',
      type: 'warning',
    })
  }
  else {
    // 调用用户小仓库的getToken方法
    userStore.getToken({
      grant_type: 'authorization_code',
      client_id: import.meta.env.VITE_OAUTH_CLIENT_ID,
      client_secret: import.meta.env.VITE_OAUTH_CLIENT_SECRET,
      redirect_uri: import.meta.env.VITE_OAUTH_REDIRECT_URI,
      code,
      state,
    })
  }
}
else {
  // 缓存state
  SET_STATE(state)
  window.location.href = `${
    import.meta.env.VITE_OAUTH_ISSUER
  }/oauth2/authorize?client_id=${
    import.meta.env.VITE_OAUTH_CLIENT_ID
  }&response_type=code&scope=openid%20profile%20message.read%20message.write&redirect_uri=${
    import.meta.env.VITE_OAUTH_REDIRECT_URI
  }&state=${state}`
}
</script>

<template>
  加载中...
</template>
